Ternary operation

In mathematics, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A. An example of a ternary operation is the product in a heap.

In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types.

Many programming languages that use C-like syntax feature a ternary operator, ?:, which defines a conditional expression. Since this operator is often the only existing ternary operator in the language, it is sometimes simply referred to as "the ternary operator", though it is more accurately referred to as the conditional operator.

Most of the languages emphasizing functional programming don't need such an operator as their regular conditional expression(s) is an expression in the first place e.g. the Scheme expression (if (> a b) a b) is equivalent in semantics to the C expression (a > b) ? a : b. This is also the case in many imperative languages, starting with ALGOL where it is possible to write result := if a > b then a else b, or Smalltalk (result := (a > b) ifTrue: [ a ] ifFalse: [ b ]) or Ruby (result = if a > b: a else b end)

Contents

Examples

C, C++, C#, Vala, Objective-C, Java, JavaScript, ActionScript

A traditional if-else construct in C, C++, C#, Vala, Objective-C, Java, JavaScript and ActionScript is written:[1]

if (a > b) {
    result = x;
}
else {
    result = y;
}

This can be rewritten as the following ternary statement:

result = a > b ? x : y;

Common Lisp

Assignment using a ternary expression in Common Lisp:

(setf result (if (> a b) x y))

Imperative form:

(if (> a b)
  (setf result x)
  (setf result y))

Perl, PHP

A traditional if-else construct in Perl or PHP is written:

if ($a > $b) {
    $result = $x;
} else {
    $result = $y;
}

Rewritten to use the ternary operator:

$result = ($a > $b) ? $x : $y;

Perl 6

Uses double "?" symbols and double "!" instead of ":" [2]:

$result = ($a > $b) ?? $x !! $y;

Python

Though it had been delayed for several years by disagreements over syntax, a ternary operator for Python was approved as Python Enhancement Proposal 308 and was added to the 2.5 release in September 2006. Python's ternary operator differs from the common ?: operator in the order of its operands. The general form is:

x if a > b else y

This form invites considering x as the normal value and y as an exceptional case. One can use the syntax

(lambda:y, lambda:x)[a > b]()

as a workaround for code that also needs to run under Python versions before 2.5. Note that operands are lazily evaluated, it is possible to remove the lambdas and function calls but the operands will be eagerly evaluated which isn't consistent with other languages' ternary operators, e.g. by using an explicitly constructed dictionary:

{True: x, False: y}[a > b]

A less reliable but simpler to read alternative is to abuse the and and or operators and write

(a > b) and x or y

but this code would break if x could be a "falsy" value (None, False, 0, an empty sequence or collection, …) as the expression would return y (whether it was truthy or falsy) instead of the (falsy) x. A possible workaround is to make x and y lists or tuples, so they are never falsy, and then grab the first element of the resulting sequence as in the following

((a > b) and [x] or [y])[0]

or

((a > b) and (x,) or (y,))[0]

Ruby

A traditional if-else construct in Ruby is written:[3]

if a > b
  result = x
else
  result = y
end

This could also be written as:

result = if a > b
  x
else
  y
end

These can be rewritten as the following ternary statement:

result = a > b ? x : y

Visual Basic

Visual Basic Version 9 has added a ternary operator, If(), in addition to the existing IIf() function that existed previously. As a true operator, it does not have the side effects and potential inefficiencies of the IIf() function.

The syntaxes of the tokens are similar: If([condition,] op1, op2) vs IIf(condition, op1, op2). As mentioned above, the function call has significant disadvantages, because the sub-expressions must all be evaluated, according to Visual Basic's evaluation strategy for function calls and the result will always be of type variant (VB) or object (VB.NET). The If()operator however does not suffer from these problems as it supports conditional evaluation and determines the type of the expression based on the types of its operands.

PL/SQL

A specific ternary operator for PL/SQL is not available, but a special case of the CASE expression works exactly as a ternary operator:

SELECT (CASE WHEN a > b THEN x ELSE y END) AS "Ternary_Example"
  FROM DUAL;

See also

References

External links